package com.tongjie.hotelbooking.sequence.service;

import com.tongjie.hotelbooking.sequence.entity.Sequence;
import com.tongjie.hotelbooking.sequence.repository.SequenceRepository;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.Date;

@Service
public class SequenceService {

    public static String ORDER_SERIAL = "ORDER_SERIAL";

    @Resource
    private SequenceRepository sequenceRepository;

    @Transactional
    public Long nextValue(String serialName) {
        this.sequenceRepository.updateCurrentValue(serialName);
        Sequence serial = this.sequenceRepository.getSequenceBySequenceName(serialName);
        return serial.getCurrentValue();
    }

    @Transactional
    public String nextOrderNumber() {
        String dateStr = DateFormatUtils.format(new Date(), "yyyyMMddhhmmss");
        this.sequenceRepository.updateCurrentValue(ORDER_SERIAL);
        Sequence serial = this.sequenceRepository.getSequenceBySequenceName(ORDER_SERIAL);
        return dateStr + serial.getCurrentValue();
    }

    @Transactional
    public void init() {
        Sequence serial = this.sequenceRepository.getSequenceBySequenceName(ORDER_SERIAL);
        if (serial == null) {
            this.sequenceRepository.save(Sequence.builder().sequenceName(ORDER_SERIAL).currentValue((long) 0).stepLength(1).build());
        }
    }

}
